﻿import clr
clr.AddReference('System')

from System.CodeDom import Compiler
from Microsoft.CSharp import CSharpCodeProvider

def Generate(code, references=None):
    CompilerParams = Compiler.CompilerParameters()

    CompilerParams.GenerateInMemory = True

    CompilerParams.TreatWarningsAsErrors = False
    CompilerParams.GenerateExecutable = False
    CompilerParams.CompilerOptions = "/optimize"

    for reference in references or []:
        CompilerParams.ReferencedAssemblies.Add(reference)

    provider = CSharpCodeProvider()
    compile = provider.CompileAssemblyFromSource(CompilerParams, code)

    if compile.Errors.HasErrors:
        raise Exception("Compile error: %r" % list(compile.Errors.List))

    return compile.CompiledAssembly